<template>
  <div class="checkout-container">
    <van-nav-bar
      title="购物车"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <div class="cart-list">
      <van-empty v-if="!cart.length" description="购物车是空的" />
      
      <template v-else>
        <van-card
          v-for="item in cart"
          :key="item.id"
          :price="item.price.toFixed(2)"
          :title="item.name"
          :thumb="item.image"
        >
          <template #num>
            <van-stepper
              v-model="item.quantity"
              min="1"
              @change="updateQuantity(item)"
            />
          </template>
          <template #footer>
            <van-button size="small" type="danger" @click="removeItem(item)">
              删除
            </van-button>
          </template>
        </van-card>
      </template>
    </div>
    
    <van-submit-bar
      :price="total * 100"
      button-text="提交订单"
      @submit="onSubmit"
    />
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { useOrderStore } from '../stores/order'
import { showToast } from 'vant'

const router = useRouter()
const orderStore = useOrderStore()

const cart = computed(() => orderStore.cart)
const total = computed(() => orderStore.cartTotal)

const onClickLeft = () => {
  router.back()
}

const updateQuantity = (item) => {
  // 数量已经在 stepper 中自动更新
}

const removeItem = (item) => {
  orderStore.removeFromCart(item.id)
  showToast('已删除')
}

const onSubmit = () => {
  if (!cart.value.length) {
    showToast('购物车是空的')
    return
  }
  
  const order = orderStore.createOrder()
  router.push(`/payment?orderId=${order.id}`)
}
</script>

<style scoped>
.checkout-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 50px;
}

.cart-list {
  padding: 10px;
}

.van-card {
  margin-bottom: 10px;
  background-color: #fff;
}
</style> 